const Controller = require('egg').Controller;

const fs = require('fs');
const path = require("path");
const sendToWormhole = require('stream-wormhole');


class UploadController extends Controller {

    async index () {

        
        const { app, ctx, config } = this;

        //ctx.logger.info('upload');

        const stream = await ctx.getFileStream();

        const noncestr = await ctx.service.util.uuid(16, 62);//Wm3WZYTPz0wzccnW

        //ctx.logger.info(stream.fields);

        const dir = stream.fields.dir;

        //const name = 'egg-multipart-test/' + path.basename(stream.filename);

        const extname = path.extname(stream.filename).toLowerCase();//文件扩展名称

        const fileName = Date.now() + noncestr + extname;   //文件名

        const name = 'image/' + dir + fileName;

        //ctx.logger.info(name);

        // 文件处理，上传到云存储等等
        let result;
        try {
          result = await app.oss.put(name, stream);

          //ctx.logger.info(result);
        } catch (err) {
          // 必须将上传的文件流消费掉，要不然浏览器响应会卡死
          //ctx.logger.info(err);
          await sendToWormhole(stream);
          throw err;
        }

        ctx.body = {
          //url: result.url,
          url: 'https://img.hidlq.com/' + result.name,
          // 所有表单字段都能通过 `stream.fields` 获取到
          fields: stream.fields,
        };


        // console.log('123411111111111111');

        // const dirName = ctx.helper.dateFtt('yyyyMMdd', new Date());//生成日期数据

        // console.log(dirName);

        // const stream = await ctx.getFileStream();

        // console.log('11233');

        // const extname = path.extname(stream.filename).toLowerCase();//文件扩展名称

        // console.log(stream);

        // const fileName = Date.now() + '' + Number.parseInt(Math.random() * 10000) + extname;//文件名

        // const target = path.join(config.baseDir,'app/public/uploads/upload',dirName,fileName); //文件存放目录位置

        // const writeStream = fs.createWriteStream(target); //存储文件 创造可写流

        // const streamPipe = stream.pipe(writeStream); //文件存储等待机制 将可读性流写入可写流


        // const r1 = await app.oss.put(fileName,target); //阿里云图片上传

        // ctx.helper.success(r1);


        // console.log(r1);
        // const { ordercode } = ctx.request.body;

        // ctx.logger.info(ordercode);

        // const result = await ctx.service.order.updateSmsState(ordercode, '1', '2');

        // if(result == 1){
        //     ctx.helper.success('发送中');
        // }else{
        //     ctx.helper.success('发送失败');
        // }

    }
    
}
module.exports = UploadController;